package me.monster.smarttraffic.tool;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.monster.smarttraffic.bo.BaseResponse;

/**
 * @description
 * @author: Created jiangjiwei in 2020-01-29 13:44
 */
public class RxUtils {

    public static <T> ObservableTransformer<T, T> applyToMain() {
        return new ObservableTransformer<T, T>() {
            @Override
            public ObservableSource<T> apply(Observable<T> upstream) {
                return upstream.subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }

    public static <T> ObservableTransformer<BaseResponse<T>, T> transform() {
        return new ObservableTransformer<BaseResponse<T>, T>() {
            @Override
            public ObservableSource<T> apply(Observable<BaseResponse<T>> upstream) {
                return upstream.compose(applyToMain())
                        .compose(handleResult());
            }
        };
    }

    public static <T> ObservableTransformer<BaseResponse<T>, T> handleResult() {
        return new ObservableTransformer<BaseResponse<T>, T>() {
            @Override
            public ObservableSource<T> apply(Observable<BaseResponse<T>> baseResponseObservable) {
                return baseResponseObservable.flatMap((Function<BaseResponse<T>, ObservableSource<T>>) this::processRep);
            }

            private ObservableSource<T> processRep(BaseResponse<T> response) {
                if (response.isSuccess()) {
                    return Observable.just(response.getData());
                } else {
                    return Observable.error(new Exception(response.getMsg()));
                }
            }
        };
    }
}
